﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;
using ShredTheLog.ViewModels;
using ShredTheLog.Api;

namespace System.Collections.ObjectModel
{
    public static class Extensions
    {
        public static void AddRange<T>(this ICollection<T> collection1, IEnumerable<T> collection2)
        {
            Contract.Requires(collection1 != null);
            Contract.Requires(collection2 != null);

            collection2.ForEach(i => collection1.Add(i));
        }

        public static void Merge<TUserInfo1, TUserInfo2>(this ICollection<TUserInfo1> collection1, IEnumerable<TUserInfo2> collection2, Func<TUserInfo2, TUserInfo1> factory)
            where TUserInfo1 : IUserInfo
            where TUserInfo2 : IUserInfo
        {
            Contract.Requires(collection1 != null);
            Contract.Requires(collection2 != null);
            Contract.Requires(factory != null);

            var usersToRemove = collection1.Cast<IUserInfo>().Except(collection2.Cast<IUserInfo>(), UidEqualityComparer.Instance).ToArray();
            usersToRemove.ToArray().ForEach(i => collection1.Remove((TUserInfo1)i));
            var usersToAdd = collection2.Cast<IUserInfo>().Except(collection1.Cast<IUserInfo>(), UidEqualityComparer.Instance).ToArray();
            usersToAdd.ForEach(u => collection1.Add(factory((TUserInfo2)u)));
        }

    }

    public sealed class UidEqualityComparer : EqualityComparer<IUserInfo>
    {
        public override bool Equals(IUserInfo x, IUserInfo y)
        {
            return x.Uid == y.Uid;
        }

        public override int GetHashCode(IUserInfo obj)
        {
            return obj.Uid;
        }

        public static readonly UidEqualityComparer Instance = new UidEqualityComparer();
    }
}
